<template>
  <div class="app-container">
    <el-container>
      <el-aside :class="isShow ? 'max-width' : 'min-width'">
        <div class="expand" @contextmenu.prevent="handleExpand" @click="handleExpand">
          <i :class="isShow ? 'el-icon-caret-left' : 'el-icon-caret-right'"></i>
        </div>
        <div class="left-content" v-show="isShow">
          <el-row :gutter="10" style="margin-bottom: 0.3125rem;">
            <el-col :span="1.5">
              <el-dropdown @command="handleAdd" style="margin-right: 5px;">
                <el-button type="primary" plain size="mini" :loading="loading">
                  添加<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="EDITOR">editor</el-dropdown-item>
                  <el-dropdown-item command="DOC">doc</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handlerBatchDelete"
                :loading="loading" title="清除空目录">清除
              </el-button>
            </el-col>
          </el-row>

          <el-header style="height: 30px;">编辑器</el-header>
          <el-collapse accordion>
            <div class="el-collapse-box" v-for="item in editorArr">
              <div class="el-collapse-box-doc" v-if="item.type=='EDITOR'" @click="() => handleRowClick(item)">
                {{item.name}}
                <div class="title-button">
                  <el-button type="text" icon="el-icon-edit-outline" size="mini" @click="() => handleEdit(item)">编辑
                  </el-button>
                  <el-button style="color: red;" type="text" icon="el-icon-delete" size="mini"
                    @click="() => deleteRow(item)">删除
                  </el-button>
                </div>

              </div>
              <el-collapse-item v-if="item.type=='EDITOR-M'" :key="item.id" :name="item.id">
                <div class="collapse-title" slot="title">
                  {{item.name}}
                  <div class="title-button">
                    <el-button type="text" icon="el-icon-edit-outline" size="mini" @click="() => handleEdit(item)">编辑
                    </el-button>
                    <el-button style="color: red;" type="text" icon="el-icon-delete" size="mini"
                      @click="() => deleteRow(item)">删除
                    </el-button>
                  </div>
                </div>
                <el-table :ref="item.id" @row-click="handleRowClick" :data="item.children" :show-header="false"
                  style="width: 100%">
                  <el-table-column prop="name" label="名称"></el-table-column>
                  <el-table-column align="right">
                    <template slot-scope="scope">
                      <el-button type="text" icon="el-icon-edit-outline" size="mini"
                        @click="() => handleEdit(scope.row)">
                        编辑</el-button>
                      <el-button style="color: red;" type="text" icon="el-icon-delete" size="mini"
                        @click="() => deleteRow(scope.row)">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
            </div>
          </el-collapse>



          <el-header style="height: 30px;">发开文档</el-header>
          <el-collapse accordion>
            <div class="el-collapse-box" v-for="item in docArr">
              <div class="el-collapse-box-doc" v-if="item.type=='DOC'" @click="() => handleRowClick(item)">
                {{item.name}}
                <div class="title-button">
                  <el-button type="text" icon="el-icon-edit-outline" size="mini" @click="() => handleEdit(item)">编辑
                  </el-button>
                  <el-button style="color: red;" type="text" icon="el-icon-delete" size="mini"
                    @click="() => deleteRow(item)">删除
                  </el-button>
                </div>
              </div>
              <el-collapse-item v-if="item.type=='DOC-M'" :key="item.id" :name="item.id">
                <div class="collapse-title" slot="title">
                  {{item.name}}
                  <div class="title-button">
                    <el-button type="text" icon="el-icon-edit-outline" size="mini" @click="() => handleEdit(item)">编辑
                    </el-button>
                    <el-button style="color: red;" type="text" icon="el-icon-delete" size="mini"
                      @click="() => deleteRow(item)">删除
                    </el-button>
                  </div>
                </div>
                <el-table :ref="item.id" @row-click="handleRowClick" :data="item.children" :show-header="false"
                  style="width: 100%">
                  <el-table-column prop="name" label="名称"></el-table-column>
                  <el-table-column align="right">
                    <template slot-scope="scope">
                      <el-button type="text" icon="el-icon-edit-outline" size="mini"
                        @click="() => handleEdit(scope.row)">
                        编辑</el-button>
                      <el-button style="color: red;" type="text" icon="el-icon-delete" size="mini"
                        @click="() => deleteRow(scope.row)">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
            </div>
          </el-collapse>

          <!--编辑框-->
          <info-dialog v-if="dialogVisible" :handle-type="handleType" :dialog-visible="dialogVisible"
            :dialog-data="dialogData" :parent-id="parentId" :grand-parent-id="grandParentId" @closed="dialogClose"
            @refresh="refreshLoadTree" @refreshAll="load" />
        </div>
      </el-aside>

      <el-main style="padding: 0;">
        <template>
          <div style="height:100%;">
            <codemirror v-if="type==='EDITOR'" v-model="fromData.json" :options="cmOption" class="code-mirror">
            </codemirror>
            <mavon-editor v-else ref=mdedit style="height: 85vh;" v-model="fromData.desc" @save="mavonSave"
              :scrollStyle="true" :ishljs="true" @imgAdd="imgAdd">
              <template slot="left-toolbar-after">
                <button type="button" @click="() => addTips('success')" class="toolbar-button" aria-hidden="true"
                  title="tip-success"><i class="el-icon-success"></i></button>
                <button type="button" @click="() => addTips('info')" class="toolbar-button" aria-hidden="true"
                  title="tip-info"><i class="el-icon-info"></i></button>
                <button type="button" @click="() => addTips('warning')" class="toolbar-button" aria-hidden="true"
                  title="tip-warning"><i class="el-icon-warning"></i></button>
                <button type="button" @click="() => addTips('danger')" class="toolbar-button" aria-hidden="true"
                  title="tip-danger"><i class="el-icon-error"></i></button>
              </template>
              <template slot="right-toolbar-after">
                <button type="button" @click="handleExport" class="toolbar-button" aria-hidden="true">
                  <i class="el-icon-printer"></i></button>
              </template>
            </mavon-editor>

          </div>
        </template>
      </el-main>
    </el-container>
  </div>
</template>
<script>
  import {
    loadAPIs,
    saveAPI,
    deleteAPI,
    uploadImage,
    deleteImages,
    deleteFolders
  } from '@/api/cloud/docApi'
  import {
    isOk
  } from '@/utils/request'
  import {
    addTips
  } from '@/utils/mavon'
  import {
    mavonEditor
  } from 'mavon-editor'
  import {
    codemirror
  } from 'vue-codemirror'

  import 'mavon-editor/dist/css/index.css'

  import 'codemirror/lib/codemirror.css'
  import 'codemirror/theme/monokai.css'
  import 'codemirror/theme/base16-light.css'
  import 'codemirror/mode/javascript/javascript.js'
  import 'codemirror/keymap/emacs.js'
  import 'codemirror/addon/edit/closebrackets.js'

  import tips from 'markdown-it-tips'
  import InfoDialog from './components/InfoDialog.vue'

  export default {
    name: 'docApi',
    components: {
      InfoDialog,
      mavonEditor,
      codemirror
    },
    data() {
      return {
        queryForm: {
          keywords: undefined,
          rootId: '0'
        },
        cmOption: {
          tabSize: 2, // tab
          styleActiveLine: true, // 高亮选中行
          lineNumbers: true, // 显示行号
          lineWrapping: true,
          styleSelectedText: true,
          line: true,
          foldGutter: true, // 块槽
          gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
          highlightSelectionMatches: {
            showToken: /\w/,
            annotateScrollbar: true
          },
          mode: {
            name: 'javascript',
            json: true
          },
          hintOptions: {
            completeSingle: false
          },
          keyMap: 'emacs',
          matchBrackets: true,
          showCursorWhenSelecting: true,
          theme: 'monokai', // 主题
          extraKeys: {
            'Ctrl': 'autocomplete'
          }
        },
        maps: new Map(),
        docArr: [],
        editorArr: [],
        status: 0,
        images: '',
        loading: false,
        isShow: true,
        dialogVisible: false,
        type: 'M',
        dialogData: {},
        /* 0-新增  1-编辑  2-新增子菜单  3-添加权限点*/
        handleType: '',
        parentId: '',
        grandParentId: '',
        activeName: '1',
        fromData: {
          id: '',
          name: '',
          json: null,
          desc: '',
          deschtml: ''
        }
      }
    },
    computed: {},
    mounted() {
      this.$refs.mdedit.markdownIt.use(tips, {
        links: false
      })
    },
    created() {
      this.load()
    },
    methods: {
      load(tree, treeNode, resolve) {
        loadAPIs().then(rsp => {
          console.log(rsp.result);
          if (isOk(rsp)) {
            this.docArr = rsp.result.doc
            this.editorArr = rsp.result.editor
          }
        })
      },
      dialogClose: function(e) {
        /* 关闭弹窗 */
        this.dialogVisible = e
        this.dialogData = {}
      },
      dialogShow: function(e) {
        /* 打开弹窗 */
        this.dialogVisible = true
      },
      handleAdd: function(command) {
        this.dialogShow()
        this.handleType = command
        this.parentId = ''
        this.options = this.dataArr
      },
      handleEdit: function(row) {
        /* 编辑 */
        this.dialogShow()
        this.handleType = '1'
        this.parentId = row.parentId
        Object.assign(this.dialogData, row)
      },
      handlerBatchDelete: function() {
        deleteFolders().then(response => {
          let type = "warning"
          if (isOk(response)) {
            type = 'success'
            this.load()
          }
          this.$message({
            message: response.result,
            type: type,
            duration: 500
          })
        })
      },
      deleteRow: function(rows) {
        /* 删除行 */
        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteAPI({
            id: rows.id
          }).then(response => {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 500
            })
            const {
              parentId
            } = rows // 取出当前删除行的父节点id
            const parentIds = '' + parentId
            if (parentIds === '0') {
              this.queryForm.rootId = '0'
              this.load()
            } else {
              this.refreshLoadTree(parentIds)
            }
          })
        })
      },
      refreshLoadTree: function(parentId, grandParentId) {
        /* 局部刷新列表 */
        if (this.maps.get(parentId)) {
          const {
            tree,
            treeNode,
            resolve
          } = this.maps.get(parentId) // 根据父节点id取出对应的节点数据
          this.$set(this.$refs.table.store.states.lazyTreeNodeMap, parentId, []) // 将对应节点下的数据清空，从而实现数据的重新加载
          this.load(tree, treeNode, resolve)
        } else {
          if (this.maps.get(grandParentId)) {
            const {
              tree,
              treeNode,
              resolve
            } = this.maps.get(grandParentId)
            this.$set(this.$refs.table.store.states.lazyTreeNodeMap, grandParentId, [])
            this.load(tree, treeNode, resolve)
          } else {
            this.load()
          }
        }
      },
      mavonSave: function(value, render) {
        this.fromData.desc = value;
        this.fromData.deschtml = render;
        saveAPI(this.fromData).then(rsp => {
          if (isOk(rsp)) {
            this.status = 1;
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.load()
          }
        })
      },
      collapsChange: function(e) {
        console.log(e)
      },
      imgAdd: function(pos, file) {
        uploadImage({
          file: file
        }).then(res => {
          if (res.code == 200) {
            this.$refs.mdedit.$img2Url(pos, process.env.VUE_APP_BASE_API + '/API/OPEN/thumbnail/' + res.result)
          }
        });
      },
      addTips: function(e) {
        addTips(this.$refs.mdedit, e);
      },
      handleExport(e) {
        console.log('失败');
      },
      handleExpand: function() {
        this.isShow = !this.isShow
      },
      handleRowClick: function(row, column, event) {
        this.type = row.type
        if (this.status == 0 && this.images) {
          //删除图片
          deleteImages({
            ids: this.images.substring(0, this.images.length - 1)
          }).then(rsp => {
            if (isOk(rsp)) {
              this.status = 0
              this.images = ''
            }
          })
        }
        if (row.type == 'DOC') {
          this.fromData.id = row.id
          this.fromData.name = row.name
          this.fromData.desc = row.desc || ''
          this.fromData.deschtml = row.deschtml || ''
        }
        if (row.type == 'EDITOR') {
          this.fromData.id = row.id
          this.fromData.name = row.name
          this.fromData.json = JSON.parse(row.json);
        }
      },
    }

  }
</script>


<style scoped>
  .app-container {
    padding: 5px;
  }

  /deep/.el-aside {
    height: 85vh;
    padding: 0;
    padding-right: 17px;
    position: relative;
    border: 1px solid #eaeefb;
    background: none;
    margin-left: 5px;
    margin-bottom: 0;
  }

  /deep/.el-aside .expand {
    width: 17px;
    height: 100%;
    background-color: #fff;
    color: #d3dce6;
    position: absolute;
    right: 0;
    border-left: 1px solid #eaeefb;
  }

  /deep/.expand:hover {
    cursor: pointer;
    color: #409eff;
    background-color: #f9fafc;
  }

  /deep/.expand i {
    position: absolute;
    top: 40%;
  }

  /deep/.collapse-title {
    flex: 1 0 90%;
    order: 1;
  }

  /deep/.el-collapse-item__header {
    flex: 1 0 auto;
    order: -1;
  }

  /deep/.el-collapse-item__header .title-button {
    display: none;
    float: right;
    margin-right: 10px;
  }

  /deep/.el-collapse-item__header:hover .title-button {
    right: 10px;
    display: inline-block;
  }

  /deep/.el-collapse-box-doc .title-button {
    display: none;
    float: right;
    margin-right: 10px;
  }

  /deep/.el-collapse-box-doc:hover .title-button {
    right: 10px;
    display: inline-block;
  }

  /deep/.el-collapse-box:not(:last-child) {
    border-bottom: 1px solid #e6ebf5;
  }

  .el-collapse-box-doc {
    height: 48px;
    margin-left: 25px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
  }

  /deep/.max-width {
    width: 380px !important;
  }

  /deep/.min-width {
    width: 17px !important;
  }

  /deep/.el-main {
    padding-top: 0px;
    border-left: 1px solid #eaeefb;
  }

  /deep/.el-collapse-item__header,
  .el-collapse-item__wrap {
    padding-left: 10px;
  }

  /deep/ .el-collapse-item__content {
    padding-bottom: 1px;
  }

  /deep/.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  /deep/.show-hide:hover :nth-child(2) {
    display: inline-block !important;
  }


  /deep/.toolbar-button {
    background-color: #f5f7fa00;
    box-sizing: border-box;
    display: inline-block;
    cursor: pointer;
    height: 28px px;
    width: 28px;
    margin: 6px 0 5px 0px;
    font-size: 14px;
    padding: 4.5px 6px 5px 3.5px;
    color: #757575;
    border-radius: 5px;
    text-align: center;
    background: none;
    border: none;
    outline: none;
    line-height: 1;
  }

  /deep/.toolbar-button i {
    width: 0.875rem;
    height: 0.875rem;
    margin: 0 2.8px;
  }

  /deep/ .md-tip {
    background-color: #f2f6fc;
  }

  /deep/ .md-tip p {
    border-bottom-right-radius: 2px;
    padding: 14px 30px;
    position: relative;
    font-size: 14px;
    margin: 14px 0;
  }

  /deep/ .md-tip p::before {
    border-radius: 100%;
    color: #fff;
    content: "!";
    font-family: Arial, sans-serif;
    font-size: 14px;
    font-weight: 700;
    left: -12px;
    line-height: 20px;
    position: absolute;
    height: 20px;
    width: 20px;
    text-align: center;
    top: 14px;
  }

  /deep/ .md-tip-success {
    color: #67c23a;
    border-left: 4px solid #67c23a;
  }

  /deep/ .md-tip-success p::before {
    background-color: #67c23a;
  }


  /deep/ .md-tip-info {
    color: #1890ff;
    border-left: 4px solid #1890ff;
  }

  /deep/ .md-tip-info p::before {
    background-color: #1890ff;
  }

  /deep/ .md-tip-warning {
    color: #e6a23c;
    border-left: 4px solid #e6a23c;
  }

  /deep/ .md-tip-warning p::before {
    background-color: #e6a23c;
  }

  /deep/ .md-tip-danger {
    color: #f56c6c;
    border-left: 4px solid #f56c6c;
  }

  /deep/ .md-tip-danger p::before {
    background-color: #f56c6c;
  }

  /deep/ .md-tip-error {
    color: #f56c6c;
    border-left: 4px solid #f56c6c;
  }

  /deep/ .md-tip-error p::before {
    background-color: #f56c6c;
  }

  /deep/.cell {
    padding: 0px;
  }

  /deep/ td:last-child {
    padding-right: 10px;
  }

  /deep/.el-table::before {
    left: 0;
    bottom: 0;
    width: 100%;
    height: 0px;
  }

  /* /deep/.el-table__expanded-cell {
    padding: 0px !important;
  }

  /deep/.expand-table td {
    border-bottom: 0px solid #dfe6ec;
  }

  /deep/.expand-table table .el-table__row td:first-child {
    padding-left: 30px;
  } */

  /* /deep/.el-table__expanded-cell {
    padding: 0px !important;
  } */

  /deep/.el-table td {
    border-bottom: 0px solid #dfe6ec;
  }

  /deep/.el-table .el-table__row td:first-child {
    padding-left: 30px;
  }

  /deep/.code-mirror {
    font-size: 14px;
    height: 85vh;
  }

  /deep/.cm-s-monokai {
    height: 100%;
  }

  .el-header {
    background-color: #f5f7fa;
    color: #333;
    text-align: left;
    line-height: 30px;
  }
</style>
